package com.amit.hibernate;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;

public class HibernateTemplate {

	public static List<Customer> findList(String hql,Object...args) {
		Transaction tx=null;
		List list=null;
		
		
		try
		{
		SessionFactory sessionfactory=HibernateUtil.getfactory();	
		Session session=sessionfactory.openSession();
		 tx=session.beginTransaction();
		
		Query q=session.createQuery(hql);
		for(int i=0;i<args.length;i++)
		{
			q=q.setParameter(i, args[i]);
		}
		list=q.list();
		tx.commit();
		session.close();
		}
		catch (Exception e) {
			if(tx!=null)
			{
				tx.rollback();
			}
			
		}
		
		return list;
	}
	
	
	public static List<Customer> findList(String hql,int start,int total,Object...args) {
		Transaction tx=null;
		List list=null;
		
		
		try
		{
		SessionFactory sessionfactory=HibernateUtil.getfactory();	
		Session session=sessionfactory.openSession();
		 tx=session.beginTransaction();
		
		Query q=session.createQuery(hql);
		q=q.setFirstResult(start);
		q=q.setMaxResults(total);
		for(int i=0;i<args.length;i++)
		{
			q=q.setParameter(i, args[i]);
		}
		list=q.list();
		tx.commit();
		session.close();
		}
		catch (Exception e) {
			if(tx!=null)
			{
				tx.rollback();
			}
			
		}
		
		return list;
	}


	public static Object findObject(String hql, Object...args) {
		Transaction tx=null;
		List list=null;
		Object obj=null;
		
		
		try
		{
		SessionFactory sessionfactory=HibernateUtil.getfactory();	
		Session session=sessionfactory.openSession();
		 tx=session.beginTransaction();
		
		Query q=session.createQuery(hql);
		
		for(int i=0;i<args.length;i++)
		{
			q=q.setParameter(i, args[i]);
		}
		obj=q.uniqueResult();
		tx.commit();
		session.close();
		}
		catch (Exception e) {
			if(tx!=null)
			{
				tx.rollback();
			}
			
		}
		
		return obj;
	}

}
